<?php

namespace App\Models\ChatGroup;

use App\Models\BaseModel;
use App\Models\Shop\ShopModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Models\Workflow\WorkflowTemplateModel;
use App\Service\BaseService;
use App\Service\ChatGroup\ChatGroupMessageReadService;
use App\Service\Rms\ShopService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ChatGroupSessionModel extends BaseModel
{
    protected $fillable = [
        'shopId',
        'groupId',
        'isNew',
        'lastMsgTime',
        'robotIn',
        'serveIn',
        'status',
        'serveUid',
        'serveName',
        'isAnswer',
        'serveInTime',
    ];

    protected $table = 'chat_group_session';

    const IS_NEW_YES = 1;
    const IS_NEW_NO  = 0;

    const ROBOT_IN_YES = 1;
    const ROBOT_IN_NO  = 0;

    const SERVE_IN_NO  = 0;
    const SERVE_IN_YES = 1;
    const SERVE_IN_ING = 2;

    const SERVE_IN_GROUP_TEXT = [
        self::SERVE_IN_NO  => 'AI值班',
        self::SERVE_IN_YES => '处理中',
        self::SERVE_IN_ING => '呼叫中',
    ];

    const STATUS_OK    = 1;
    const STATUS_CLOSE = 0;

    /**
     * 获取进行中的session
     * @param int $groupId
     * @return Builder|Model|object|null
     */
    public static function getActiveSession(int $groupId)
    {
        return self::query()
                   ->where('groupId', $groupId)
                   ->where('isNew', ChatGroupSessionModel::IS_NEW_YES)
                   ->where('status', ChatGroupSessionModel::STATUS_OK)
                   ->first();
    }

    /**
     * 根据条件更新
     *
     * @param array $where
     * @param array $updateData
     * @return int
     */
    public static function updateColumn(array $where, array $updateData): int
    {
        return self::query()->where($where)->update($updateData);
    }

    /**
     * 群列表
     *
     * @param int $userId
     * @param int $pageSize
     * @param int $pageNum
     * @param array $shopIds
     * @param int $shopStatus
     * @param int $serveIn
     * @param array $permissionLists
     * @param string $content
     * @param int $shopCode
     * @return array
     */
    public function getGroupLists(
        int $userId = 0,
        int $pageSize = 10,
        int $pageNum = 0,
        array $shopIds = [],
        int $shopStatus = -1,
        int $serveIn = -1,
        array $permissionLists = [],
        string $content = '',
        int $shopCode = 0
    ): array {
        $select = [
            'chat_groups.id',
            'chat_groups.shopId',
            'kf_shops.shopCode',
            'kf_shops.status as shopStatus',
            'kf_shops.name as shopName',
            'chat_groups.name',
            'chat_group_session.serveIn',
            'chat_group_session.serveInTime',
            'chat_group_session.lastMsgTime',
            'chat_group_session.groupId'
        ];
        $list   = self
            ::newQuery()
            ->leftJoin('chat_groups', 'chat_groups.id', 'chat_group_session.groupId')
//            ::leftJoin('chat_groups', 'chat_groups.id', 'chat_group_session.groupId')
            ->where('isNew', self::IS_NEW_YES)
            ->when(count($shopIds) > 0, function ($query) use ($shopIds) {
                $query->whereIn('chat_groups.shopId', $shopIds);
            })
            ->when($serveIn > -1, function ($query) use ($serveIn) {
                $query->where('chat_group_session.serveIn', $serveIn);
            })
            ->when($shopCode > 0, function ($query) use ($shopCode) {
                $shopInfo = ShopModel::getShopInfoByParams(['shopCode' => $shopCode]);
                if (!$shopInfo) {
                    BaseService::throwErr("店铺不存在");
                }
                $query->whereIn('chat_groups.shopId', [$shopInfo->id]);
            })
            ->where(function ($query) use ($permissionLists, $userId) {
                if (in_array('chatgroup.listall', $permissionLists)) {
                    // 看全部 - 没起作用先注释了
//                    $query->leftJoin('chat_group_users', 'chat_group_users.groupId', 'chat_group_session.groupId');
                } elseif (in_array('chatgroup.list', $permissionLists)) {
                    // 看自己
                    $query->leftJoin('chat_group_users', 'chat_group_users.groupId', 'chat_group_session.groupId')
                          ->where('chat_group_users.userId', $userId);
                } else {
                    // 没权限
                    BaseService::throwErr("暂无权限");
                }
            })
            ->when(!empty($content), function ($query) use ($content, &$select) {
                // 查询相关的聊天记录
                $list = ChatGroupHistoryModel::query()
                                             ->select(DB::raw('groupId,MAX( createdAt ) AS latest ,id'))
                                             ->where('content', 'like', "%{$content}%")
                                             ->where('createdAt', '>', time() - 86400 * 7)
                                             ->where('type', 'text')
                                             ->groupBy('groupId')
//                                             ->where('senderUid', '!=', ChatGroupUserModel::KUA_XIAO_FU_USER_ID)
                                             ->orderByDesc('latest')
                                             ->limit(20)
                                             ->get();

                $ids = $list->pluck('id');

                $query->leftJoin('chat_group_history', 'chat_group_history.groupId', 'chat_group_session.groupId')
                      ->whereIn('chat_group_history.id', $ids);

                $select[] = 'chat_group_history.content';
                $select[] = 'chat_group_history.id as historyId';
                $select[] = 'chat_group_history.createdAt as historyCreatedAt';
            })
            ->leftJoin('kf_shops', 'kf_shops.id', 'chat_groups.shopId')
            ->when($shopStatus > -1, function ($query) use ($shopStatus) {
                $query->where('kf_shops.status', $shopStatus);
            })
            // 根据呼叫时间正序, 根据最后一条记录倒叙
//            ->orderByRaw('CASE WHEN serveInTime = 0 THEN 4102415999 ELSE 0 END, serveInTime ASC,lastMsgTime DESC')
            ->orderByRaw('lastMsgTime DESC')
            ->select($select)
            ->groupBy('chat_groups.id')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $readMessageService = $userId ? new ChatGroupMessageReadService($userId) : null;

        return BaseService::pageLists($list, function ($item) use ($readMessageService) {
            return [
                'sessionId'   => $item->id,
                'groupId'     => $item->groupId,
                'unreadNums'  => $readMessageService ? $readMessageService->getUnreadNums($item->id) : 0,
                'shopId'      => $item->shopId,
                'shopCode'    => $item->shopCode,
                'shopName'    => $item->shopName,
                'shopStatus'  => $item->shopStatus,
                'name'        => $item->name,
                'serveIn'     => $item->serveIn,
                'lastMsgTime' => $item->lastMsgTime,
                'serveInTime' => $item->serveInTime,
                'groupAvatar' => 'https://file.51kuafu.com/5e/e8/07579232ee7a6d8e91a35752400830789d3bcd8ec874569b4124f1d2028f.jpeg',
                'historyId'   => $item->historyId ?? 0,
                'content'     => $item->content ?? '',
            ];
        });
    }
}
